'use client';

import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Modal, Form, Input, DatePicker, TimePicker, Select, Rate, message, Tabs, Tag, Spin, Space, Avatar } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import Layout from '@/components/Layout';
import { 
  createInterview,
  getInterviews,
  getAllInterviews,
  cancelInterviews,
  getInterviewStatusText,
  formatInterviewTime,
  validateInterviewTime,
  updateInterview,
  getInterviewSituations,
  updateInterviewSituation,
  startOrEndInterview,
} from '@/lib/interview';
import { getResumeById, InterviewStatus } from '@/lib/apply';
import { InterviewDetail, InterviewSchedule, InterviewTimeStatus } from '@/types/interview';
import { getRecruitmentAnnouncements } from '@/lib/recruitment';
import { fetchEmployeeData } from '@/lib/user';
import dayjs from 'dayjs';
import { Document, Page } from 'react-pdf';
import { pdfjs } from 'react-pdf';
import { handleResumePreview, downloadFile, cleanupPreviewUrl } from '@/utils/resumeHelper';
import moment from 'moment';
import { styled } from '@mui/material/styles';

// 设置PDF.js worker
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

// 添加Ant Design DatePicker配置
const datePickerProps = {
  showTime: { format: 'HH:mm' },
  format: "YYYY-MM-DD HH:mm",
  placeholder: "请选择时间",
  style: { width: '100%' }
};

// 添加获取面试时间状态的函数
const getInterviewTimeStatus = (startTime: string, endTime: string): InterviewTimeStatus => {
  const now = dayjs();
  const start = dayjs(startTime);
  const end = dayjs(endTime);

  if (now.isBefore(start)) {
    return InterviewTimeStatus.NotStarted;
  } else if (now.isAfter(end)) {
    return InterviewTimeStatus.Completed;
  } else {
    return InterviewTimeStatus.InProgress;
  }
};

// 将状态标签改造成组件
const InterviewStatusTag: React.FC<{ 
  startTime: string; 
  endTime: string;
  interviewId: number;
}> = ({ startTime, endTime, interviewId }) => {
  const [status, setStatus] = useState<InterviewTimeStatus>(() => 
    getInterviewTimeStatus(startTime, endTime)
  );

  useEffect(() => {
    // 每秒更新一次状态
    const timer = setInterval(() => {
      const currentStatus = getInterviewTimeStatus(startTime, endTime);
      if (currentStatus !== status) {
        setStatus(currentStatus);
        // 如果状态发生变化，自动调用开始或结束接口
        if (currentStatus === InterviewTimeStatus.InProgress && status === InterviewTimeStatus.NotStarted) {
          startOrEndInterview({ interviewId, startOrEnd: 1 });
        } else if (currentStatus === InterviewTimeStatus.Completed && status === InterviewTimeStatus.InProgress) {
          startOrEndInterview({ interviewId, startOrEnd: 2 });
        }
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [startTime, endTime, status, interviewId]);

  const statusConfig: Record<InterviewTimeStatus, { color: string; text: string }> = {
    [InterviewTimeStatus.NotStarted]: {
      color: 'blue',
      text: '未开始'
    },
    [InterviewTimeStatus.InProgress]: {
      color: 'green',
      text: '进行中'
    },
    [InterviewTimeStatus.Completed]: {
      color: 'gray',
      text: '已结束'
    }
  };

  const config = statusConfig[status];
  return <Tag color={config.color}>{config.text}</Tag>;
};

// 1. 修改判断函数，检查是否有任何面试者通过或不通过
const canAdjustInterview = (interview: InterviewDetail): boolean => {
  const details = interview.interviewDetails || [];
  return !details.some(
    (detail: { status: number; result: number }) => 
      detail.status === 1 && (detail.result === 1 || detail.result === 2)
  );
};

// 添加自动检查面试时间的函数
const checkInterviewTimes = async (interviews: InterviewDetail[]) => {
  const now = dayjs();
  
  for (const interview of interviews) {
    const startTime = dayjs(interview.startTime);
    const endTime = dayjs(interview.endTime);
    const timeStatus = getInterviewTimeStatus(interview.startTime, interview.endTime);

    // 检查是否需要开始面试
    if (now.isAfter(startTime) && timeStatus === InterviewTimeStatus.NotStarted) {
      console.log('面试自动开始:', {
        interviewId: interview.id,
        interviewName: interview.name,
        startTime: interview.startTime
      });
      
      try {
        const response = await startOrEndInterview({
          interviewId: interview.id,
          startOrEnd: 1
        });
        
        if (response.code === 1) {
          console.log('面试已自动开始:', interview.name);
        } else {
          console.error('面试自动开始失败:', response.msg);
        }
      } catch (error) {
        console.error('面试自动开始出错:', error);
      }
    }

    // 检查是否需要结束面试
    if (now.isAfter(endTime) && timeStatus === InterviewTimeStatus.InProgress) {
      console.log('面试自动结束:', {
        interviewId: interview.id,
        interviewName: interview.name,
        endTime: interview.endTime
      });
      
      try {
        const response = await startOrEndInterview({
          interviewId: interview.id,
          startOrEnd: 2
        });
        
        if (response.code === 1) {
          console.log('面试已自动结束:', interview.name);
        } else {
          console.error('面试自动结束失败:', response.msg);
        }
      } catch (error) {
        console.error('面试自动结束出错:', error);
      }
    }
  }
};

const StyledAvatar = styled(Avatar)({
  backgroundColor: '#0050b3',
  width: 36,
  height: 36,
  position: 'relative',
  zIndex: 1
});

const InterviewManagementPage = () => {
  // 移动所有状态声明到组件内部
  const [loading, setLoading] = useState(false);
  const [interviews, setInterviews] = useState<InterviewDetail[]>([]);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [createForm] = Form.useForm();
  const [recruitmentPlans, setRecruitmentPlans] = useState<any[]>([]);
  const [departments, setDepartments] = useState<any[]>([]);
  const [positions, setPositions] = useState<any[]>([]);
  const [adjustModalVisible, setAdjustModalVisible] = useState(false);
  const [adjustForm] = Form.useForm();
  const [currentInterview, setCurrentInterview] = useState<InterviewDetail | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [interviewDetails, setInterviewDetails] = useState<any[]>([]);
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [assessModalVisible, setAssessModalVisible] = useState(false);
  const [commentModalVisible, setCommentModalVisible] = useState(false);
  const [noteModalVisible, setNoteModalVisible] = useState(false);
  const [currentComment, setCurrentComment] = useState<string>('');
  const [currentNote, setCurrentNote] = useState<string>('');
  const [currentAssessee, setCurrentAssessee] = useState<any>(null);
  const [assessForm] = Form.useForm();
  const [interviewers, setInterviewers] = useState<any[]>([]);
  const [resumeModalVisible, setResumeModalVisible] = useState(false);
  const [currentResume, setCurrentResume] = useState<any>(null);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [resumeLoading, setResumeLoading] = useState(false);
  const [numPages, setNumPages] = useState<number>(0);
  const [activeTab, setActiveTab] = useState<string>('all');
  const [personalInterviews, setPersonalInterviews] = useState<InterviewDetail[]>([]);
  const [personalLoading, setPersonalLoading] = useState(false);
  const [personalTotal, setPersonalTotal] = useState(0);
  const [personalCurrentPage, setPersonalCurrentPage] = useState(1);
  const [personalPageSize, setPersonalPageSize] = useState(10);
  const [selectedResult, setSelectedResult] = useState<number | null>(null);

  // 优化数据加载的 useEffect
  useEffect(() => {
    const controller = new AbortController();

    const loadData = async () => {
      try {
        setLoading(true);
        await Promise.all([
          loadRecruitmentPlans(),
          loadInterviewers(),
          activeTab === 'all' ? loadInterviews() : loadPersonalInterviews()
        ]);
      } catch (error: any) {
        if (error.name !== 'CanceledError') {
          console.error('初始化数据加载失败:', error);
          message.error('初始化数据加载失败');
        }
      } finally {
        setLoading(false);
      }
    };

    loadData();

    return () => {
      controller.abort();
    };
  }, [activeTab, currentPage, pageSize, personalCurrentPage, personalPageSize]);

  // 添加监听表单值变化的effect
  useEffect(() => {
    const result = assessForm.getFieldValue('result');
    setSelectedResult(result);
  }, [assessForm]);

  // 2. 修改处理面试开始和结束的函数
  const handleStartOrEndInterview = async (record: InterviewDetail, startOrEnd: number) => {
    try {
      // 检查面试时间
      const now = dayjs();
      const startTime = dayjs(record.startTime);
      const endTime = dayjs(record.endTime);

      // 开始面试时的时间检查
      if (startOrEnd === 1) {
        if (now.isBefore(startTime)) {
          message.error('面试还未到开始时间');
          return;
        }
        if (now.isAfter(endTime)) {
          message.error('已超过面试结束时间');
          return;
        }
      }
      // 结束面试时的时间检查
      else if (startOrEnd === 2) {
        if (now.isBefore(startTime)) {
          message.error('面试还未开始');
          return;
        }
      }

      // 调用面试开始/结束接口
      const response = await startOrEndInterview({ 
        interviewId: record.id, 
        startOrEnd 
      });

      if (response.code === 1) {
        message.success(startOrEnd === 1 ? '面试已开始' : '面试已结束');
        
        // 刷新面试列表
        loadInterviews();
      } else {
        message.error(response.msg || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  // 加载面试列表
  const loadInterviews = async () => {
    try {
      setLoading(true);
      const response = await getAllInterviews({
        page: currentPage,
        pageSize
      });

      if (response.code === 1) {
        setInterviews(response.data.row);
        setTotal(response.data.total);
      } else if (response.code === 0) {
        // 特殊处理 code === 0 的情况
        console.warn('获取面试列表返回 code 0:', response.msg);
        setInterviews([]);
        setTotal(0);
      } else {
        message.error(response.msg || '获取面试列表失败');
      }
    } catch (error: any) {
      if (error.name === 'CanceledError') {
        console.log('面试列表加载已取消');
        return;
      }
      console.error('获取面试列表失败:', error);
      message.error('获取面试列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载招聘计划
  const loadRecruitmentPlans = async () => {
    try {
      const response = await getRecruitmentAnnouncements();
      console.log('获取到的原始响应:', response);
      
      if (response.code === 1) {
        console.log('获取到的招聘计划数据:', {
          plans: response.data,
          firstPlan: response.data[0],
          depts: response.data[0]?.depts
        });
        setRecruitmentPlans(response.data);
      } else {
        message.error(response.msg || '获取招聘计划失败');
      }
    } catch (error) {
      console.error('获取招聘计划失败:', error);
    }
  };

  // 修改表单相关的函数引用
  const handlePlanChange = (planId: number) => {
    const plan = recruitmentPlans.find(p => p.planId === planId);
    if (plan) {
      setDepartments(plan.depts || []);
      setPositions([]); // 清空岗位列表
      createForm.setFieldsValue({ 
        deptId: undefined, 
        positionNumber: undefined 
      });
    } else {
      setDepartments([]);
      setPositions([]);
    }
  };

  // 修改部门变更处理函数
  const handleDepartmentChange = (deptId: string) => {
    const department = departments.find(d => d.numbering === deptId);
    if (department) {
      setPositions(department.positions || []);
      createForm.setFieldsValue({ 
        positionNumber: undefined 
      });
    } else {
      setPositions([]);
    }
  };

  // 添加部门和岗位列表变化的监听
  useEffect(() => {
    console.log('部门列表已更新:', departments);
  }, [departments]);

  useEffect(() => {
    console.log('岗位列表已更新:', positions);
  }, [positions]);

  // 处理创建面试
  const handleCreate = async (values: any) => {
    try {
      const startTime = values.startTime;
      const endTime = values.endTime;
      const now = moment();

      // 详细的时间验证
      if (!startTime || !endTime) {
        message.error('请选择面试开始和结束时间');
        return;
      }

      if (startTime.isBefore(now)) {
        message.error('面试开始时间不能早于当前时间');
        return;
      }

      if (endTime.isBefore(startTime)) {
        message.error('面试结束时间不能早于开始时间');
        return;
      }

      if (endTime.diff(startTime, 'hours') > 24) {
        message.error('面试时间跨度不能超过24小时');
        return;
      }

      const schedule: InterviewSchedule = {
        ...values,
        startTime: startTime.format('YYYY-MM-DDTHH:mm:ss'),
        endTime: endTime.format('YYYY-MM-DDTHH:mm:ss'),
        interviewerIds: values.interviewerIds.join(',')
      };

      const response = await createInterview(schedule);
      if (response.code === 1) {
        message.success('面试安排创建成功');
        setCreateModalVisible(false);
        createForm.resetFields();
        loadInterviews();
      } else {
        message.error(response.msg || '创建面试安排失败');
      }
    } catch (error) {
      console.error('创建面试安排失败:', error);
      message.error('创建面试安排失败');
    }
  };

  // 处理取消面试
  const handleCancel = async (id: number) => {
    Modal.confirm({
      title: '确认取消',
      content: '确定要取消这场面试吗？',
      onOk: async () => {
        try {
          const response = await cancelInterviews([id]);
          if (response.code === 1) {
            message.success('面试已取消');
            loadInterviews();
          } else {
            message.error(response.msg || '取消面试失败');
          }
        } catch (error) {
          console.error('取消面试失败:', error);
          message.error('取消面试失败');
        }
      }
    });
  };

  // 处理调整面试安排
  const handleAdjust = (record: InterviewDetail) => {
    setCurrentInterview(record);
    adjustForm.setFieldsValue({
      startTime: moment(record.startTime),
      endTime: moment(record.endTime),
      place: record.place,
      interviewerIds: record.interviewerIds.split(',')
    });
    setAdjustModalVisible(true);
  };

  // 提交调整
  const handleAdjustSubmit = async (values: any) => {
    try {
      if (!currentInterview) return;

      const startTime = values.startTime;
      const endTime = values.endTime;
      const now = moment();

      // 详细的时间验证
      if (!startTime || !endTime) {
        message.error('请选择面试开始和结束时间');
        return;
      }

      if (startTime.isBefore(now)) {
        message.error('面试开始时间不能早于当前时间');
        return;
      }

      if (endTime.isBefore(startTime)) {
        message.error('面试结束时间不能早于开始时间');
        return;
      }

      if (endTime.diff(startTime, 'hours') > 24) {
        message.error('面试时间跨度不能超过24小时');
        return;
      }

      const schedule: Partial<InterviewSchedule> = {
        startTime: startTime.format('YYYY-MM-DDTHH:mm:ss'),
        endTime: endTime.format('YYYY-MM-DDTHH:mm:ss'),
        place: values.place,
        interviewerIds: values.interviewerIds.join(',')
      };

      const response = await updateInterview(currentInterview.id, schedule);
      if (response.code === 1) {
        message.success('面试安排调整成功');
        setAdjustModalVisible(false);
        adjustForm.resetFields();
        loadInterviews();
      } else {
        message.error(response.msg || '调整面试安排失败');
      }
    } catch (error) {
      console.error('调整面试安排失败:', error);
      message.error('调整面试安排失败');
    }
  };

  // 修改评估初始化函数
  const handleAssess = (record: any, interview: InterviewDetail) => {
    setCurrentAssessee(record);
    setCurrentInterview(interview);
    const initialValues = {
      professionalSkills: record.professionalSkills,
      communicationSkills: record.communicationSkills,
      teamworkAbility: record.teamworkAbility,
      comments: record.comments,
      notes: record.notes,
      result: record.result
    };
    assessForm.setFieldsValue(initialValues);
    setSelectedResult(record.result);
    setAssessModalVisible(true);
  };

  // 修改评估提交函数，更新父级面试数据
const handleAssessSubmit = async (values: any) => {
  try {
    if (!values.result) {
      message.error('请选择面试结果');
      return;
    }

    setDetailsLoading(true);
    const submitParams = {
      id: currentAssessee.id,
      professionalSkills: Math.round(values.professionalSkills || 0),  // 确保是整数
      communicationSkills: Math.round(values.communicationSkills || 0),
      teamworkAbility: Math.round(values.teamworkAbility || 0),
      comments: values.comments,
      notes: values.notes,
      status: 1, // 已面试
      result: values.result // 只能是 1(通过) 或 2(不通过)
    };

    console.log('提交评估参数:', {
      原始表单数据: values,
      处理后参数: submitParams,
      当前应聘者: currentAssessee,
      当前面试: currentInterview
    });

    const response = await updateInterviewSituation(submitParams);
    console.log('评估更新响应:', {
      提交参数: submitParams,
      响应数据: response
    });

    if (response.code === 1) {
      message.success('评估更新成功');
      setAssessModalVisible(false);
      
      // 刷新面试详情
      const detailResponse = await getInterviewSituations({
        interviewId: currentInterview!.id,
        page: 1,
        pageSize: 100
      });

      console.log('刷新面试详情响应:', {
        请求参数: {
          interviewId: currentInterview!.id,
          page: 1,
          pageSize: 100
        },
        响应数据: detailResponse
      });

      if (detailResponse.code === 1) {
        setInterviewDetails(detailResponse.data.row);
        
        // 刷新面试列表，以更新按钮状态
        loadInterviews();
      } else {
        message.error(detailResponse.msg || '刷新面试详情失败');
      }
    } else {
      message.error(response.msg || '评估更新失败');
    }
  } catch (error) {
    console.error('更新评估失败:', error);
    message.error('更新评估失败');
  } finally {
    setDetailsLoading(false);
  }
};

  // 添加查看评价意见的函数
  const handleViewComment = (record: any) => {
    setCurrentComment(record.comments || '');
    setCommentModalVisible(true);
  };

  // 添加查看备注的函数
  const handleViewNote = (record: any) => {
    setCurrentNote(record.notes || '');
    setNoteModalVisible(true);
  };

  // 修改查看详情函数
  const handleViewDetails = async (record: InterviewDetail) => {
    try {
      setDetailsLoading(true);
      setCurrentInterview(record); // 保存当前面试信息
      
      const response = await getInterviewSituations({
        interviewId: record.id,
        page: 1,
        pageSize: 100
      });

      console.log('面试详情响应:', response);
      console.log('面试详情数据:', response.data?.row);

      if (response.code === 1) {
        setInterviewDetails(response.data.row);
        setDetailModalVisible(true);
      } else {
        message.error(response.msg || '获取面试详情失败');
      }
    } catch (error) {
      console.error('获取面试详情失败:', error);
      message.error('获取面试详情失败');
    } finally {
      setDetailsLoading(false);
    }
  };

  // 添加查看简历的处理函数
  const handleViewResume = async (id: number) => {
    console.log('应聘者ID:', id);
    console.log('当前记录:', currentAssessee);
    console.log('面试详情:', interviewDetails);

    if (!id) {
      message.warning('无法获取应聘者ID');
      return;
    }

    try {
      setResumeLoading(true);
      const response = await getResumeById(id);
      console.log('获取简历响应:', response);
      
      if (response.code === 1) {
        const { previewUrl, fileName, fileType } = handleResumePreview(response.data);
        setPreviewUrl(previewUrl);
        setCurrentResume({ fileName, fileType });
        setResumeModalVisible(true);
      } else {
        message.error(response.msg || '获取简历失败');
      }
    } catch (error) {
      console.error('获取简历失败:', error);
      message.error('获取简历失败');
    } finally {
      setResumeLoading(false);
    }
  };

  // 处理模态框关闭
  const handleModalClose = () => {
    if (previewUrl) {
      cleanupPreviewUrl(previewUrl);
      setPreviewUrl('');
    }
    setResumeModalVisible(false);
  };

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (previewUrl) {
        cleanupPreviewUrl(previewUrl);
      }
    };
  }, [previewUrl]);

  // 表格列定义
  const columns = [
    {
      title: '面试名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '面试地点',
      dataIndex: 'place',
      key: 'place',
    },
    {
      title: '面试轮次',
      dataIndex: 'interviewRound',
      key: 'interviewRound',
    },
    {
      title: '面试官',
      dataIndex: 'interviewerIds',
      key: 'interviewerIds',
    },
    {
      title: '招聘人数',
      dataIndex: 'recruitsNumber',
      key: 'recruitsNumber',
    },
    {
      title: '已面试/通过',
      key: 'interviewStats',
      render: (record: InterviewDetail) => 
        `${record.interviewNumber}/${record.throughNumber}`,
    },
    {
      title: '面试时间',
      key: 'time',
      render: (record: InterviewDetail) =>
        `${moment(record.startTime).format('YYYY-MM-DD HH:mm:ss')} ~ ${moment(record.endTime).format('YYYY-MM-DD HH:mm:ss')}`,
    },
    {
      title: '面试状态',
      dataIndex: 'status',
      key: 'status',
      render: (_: unknown, record: InterviewDetail) => (
        <InterviewStatusTag 
          startTime={record.startTime} 
          endTime={record.endTime}
          interviewId={record.id}
        />
      ),
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      key: 'createBy',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (record: InterviewDetail) => {
        const timeStatus = getInterviewTimeStatus(record.startTime, record.endTime);
        const canAdjust = canAdjustInterview(record);
        
        return (
          <Space>
            {/* 调整安排按钮 */}
            <Button 
              type="link" 
              onClick={() => handleAdjust(record)}
              disabled={
                timeStatus !== InterviewTimeStatus.NotStarted || 
                !canAdjust
              }
            >
              调整安排
            </Button>

            {/* 取消面试按钮 */}
            <Button 
              type="link" 
              onClick={() => handleCancel(record.id)}
              disabled={
                timeStatus !== InterviewTimeStatus.NotStarted || 
                !canAdjust
              }
            >
              取消面试
            </Button>

            {/* 查看详情按钮 */}
            <Button 
              type="link" 
              onClick={() => handleViewDetails(record)}
            >
              查看详情
            </Button>
          </Space>
        );
      },
    },
  ];

  // 添加获取员工列表的函数
  const loadInterviewers = async () => {
    try {
      const response = await fetchEmployeeData({
        page: 1,
        pageSize: 100,
        searchKeyword: '',
        status: 1
      });
      if (response.data && response.data.code === 1) {
        const employeeList = response.data.data.row.map((emp: any) => ({
          value: emp.employeeId,
          label: emp.name
        }));
        setInterviewers(employeeList);
      } else {
        message.error(response.data?.msg || '获取面试官列表失败');
      }
    } catch (error: any) {
      console.error('获取面试官列表失败:', error);
      message.error(error.message || '获取面试官列表失败');
    }
  };

  // 加载个人面试列表
  const loadPersonalInterviews = async () => {
    try {
      setPersonalLoading(true);
      const response = await getInterviews({
        page: personalCurrentPage,
        pageSize: personalPageSize
      });

      if (response.code === 1) {
        setPersonalInterviews(response.data.row);
        setPersonalTotal(response.data.total);
      } else if (response.code === 0) {
        // 特殊处理 code === 0 的情况
        console.warn('获取个人面试列表返回 code 0:', response.msg);
        setPersonalInterviews([]);
        setPersonalTotal(0);
      } else {
        message.error(response.msg || '获取个人面试列表失败');
      }
    } catch (error: any) {
      if (error.name === 'CanceledError') {
        console.log('个人面试列表加载已取消');
        return;
      }
      console.error('获取个人面试列表失败:', error);
      message.error('获取个人面试列表失败');
    } finally {
      setPersonalLoading(false);
    }
  };

  return (
    <Layout>
      <div className="p-4">
        <Card>
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            items={[
              {
                key: 'all',
                label: '全部面试',
                children: (
                  <div>
                    <div className="mb-4">
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => setCreateModalVisible(true)}
                      >
                        新增面试
                      </Button>
                    </div>
                    <Table
                      rowKey="id"
                      columns={columns}
                      dataSource={interviews}
                      loading={loading}
                      pagination={{
                        current: currentPage,
                        pageSize,
                        total,
                        onChange: (page, size) => {
                          setCurrentPage(page);
                          setPageSize(size || 10);
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条记录`,
                      }}
                    />
                  </div>
                ),
              },
              {
                key: 'personal',
                label: '我的面试',
                children: (
                  <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={personalInterviews}
                    loading={personalLoading}
                    pagination={{
                      current: personalCurrentPage,
                      pageSize: personalPageSize,
                      total: personalTotal,
                      onChange: (page, size) => {
                        setPersonalCurrentPage(page);
                        setPersonalPageSize(size || 10);
                      },
                      showSizeChanger: true,
                      showQuickJumper: true,
                      showTotal: (total) => `共 ${total} 条记录`,
                    }}
                  />
                ),
              },
            ]}
          />
        </Card>

        {/* 修改创建面试表单 */}
        <Modal
          title="新增面试"
          open={createModalVisible}
          onOk={() => createForm.submit()}
          onCancel={() => setCreateModalVisible(false)}
          width={600}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreate}
          >
            <Form.Item
              label="面试名称"
              name="name"
              rules={[{ required: true, message: '请输入面试名称' }]}
            >
              <Input placeholder="请输入面试名称" />
            </Form.Item>

            <Form.Item
              label="招聘计划"
              name="planId"
              rules={[{ required: true, message: '请选择招聘计划' }]}
            >
              <Select 
                placeholder="请选择招聘计划"
                onChange={handlePlanChange}
              >
                {recruitmentPlans.map(plan => (
                  <Option key={plan.planId} value={plan.planId}>
                    {plan.planName}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="招聘部门"
              name="deptId"
              rules={[{ required: true, message: '请选择招聘部门' }]}
            >
              <Select 
                placeholder="请选择招聘部门"
                onChange={handleDepartmentChange}
                disabled={!departments.length}
              >
                {departments.map(dept => (
                  <Option key={dept.numbering} value={dept.numbering}>
                    {dept.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="招聘岗位"
              name="positionNumber"
              rules={[{ required: true, message: '请选择招聘岗位' }]}
            >
              <Select 
                placeholder="请选择招聘岗位"
                disabled={!positions.length}
              >
                {positions.map(pos => (
                  <Option key={pos.positionNumber} value={pos.positionNumber}>
                    {pos.positionName}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="面试官"
              name="interviewerIds"
              rules={[{ required: true, message: '请选择面试官' }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择面试官"
                style={{ width: '100%' }}
                optionFilterProp="children"
                showSearch
              >
                {interviewers.map(interviewer => (
                  <Option 
                    key={interviewer.value} 
                    value={interviewer.value}
                  >
                    <StyledAvatar>
                      {interviewer.label}
                    </StyledAvatar>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="面试轮次"
              name="interviewRound"
              rules={[{ required: true, message: '请选择面试轮次' }]}
            >
              <Select placeholder="请选择面试轮次">
                <Option value={1}>第一轮</Option>
                <Option value={2}>第二轮</Option>
                <Option value={3}>终面</Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="面试地点"
              name="place"
              rules={[{ required: true, message: '请输入面试地点' }]}
            >
              <Input placeholder="请输入面试地点" />
            </Form.Item>

            <Form.Item
              label="预计招聘人数"
              name="recruitsNumber"
              rules={[{ required: true, message: '请输入预计招聘人数' }]}
            >
              <Input type="number" min={1} placeholder="请输入预计招聘人数" />
            </Form.Item>

            <Form.Item
              label="面试时间"
              required
            >
              <div style={{ display: 'flex', gap: '24px' }}>
                <Form.Item
                  name="startTime"
                  rules={[{ required: true, message: '请选择开始时间' }]}
                  style={{ flex: 1, margin: 0 }}
                >
                  <DatePicker
                    {...datePickerProps}
                    placeholder="开始时间"
                    disabledDate={(current) => {
                      // 开始时间不能选择过去的时间（不包括今天）
                      return current && current < dayjs().startOf('day');
                    }}
                    onChange={(value) => {
                      createForm.setFieldsValue({ startTime: value });
                      // 如果结束时间早于开始时间，清空结束时间
                      const endTime = createForm.getFieldValue('endTime');
                      if (endTime && value && endTime < value) {
                        createForm.setFieldsValue({ endTime: null });
                      }
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="endTime"
                  rules={[{ required: true, message: '请选择结束时间' }]}
                  style={{ flex: 1, margin: 0 }}
                >
                  <DatePicker
                    {...datePickerProps}
                    placeholder="结束时间"
                    disabledDate={(current) => {
                      const startTime = createForm.getFieldValue('startTime');
                      // 如果没有选择开始时间，不禁用任何日期
                      if (!startTime) {
                        return false;
                      }
                      // 将日期转换为开始时间的00:00
                      const currentStartOfDay = current?.startOf('day');
                      const startTimeStartOfDay = startTime.startOf('day');
                      
                      // 如果是同一天，允许选择
                      if (currentStartOfDay?.isSame(startTimeStartOfDay, 'day')) {
                        return false;
                      }
                      
                      // 如果不是同一天，只禁用早于开始时间的日期
                      return current && current.isBefore(startTimeStartOfDay);
                    }}
                    // 添加onChange处理，确保选择的具体时间不早于开始时间
                    onChange={(value) => {
                      const startTime = createForm.getFieldValue('startTime');
                      if (startTime && value && value.isBefore(startTime)) {
                        // 如果选择的时间早于开始时间，自动设置为开始时间后一小时
                        createForm.setFieldsValue({ 
                          endTime: startTime.add(1, 'hour') 
                        });
                      } else {
                        createForm.setFieldsValue({ endTime: value });
                      }
                    }}
                  />
                </Form.Item>
              </div>
            </Form.Item>
          </Form>
        </Modal>

        {/* 调整面试安排的模态框 */}
        <Modal
          title="调整面试安排"
          open={adjustModalVisible}
          onOk={() => adjustForm.submit()}
          onCancel={() => setAdjustModalVisible(false)}
          width={600}
        >
          <Form
            form={adjustForm}
            layout="vertical"
            onFinish={handleAdjustSubmit}
          >
            <Form.Item
              label="面试地点"
              name="place"
              rules={[{ required: true, message: '请输入面试地点' }]}
            >
              <Input placeholder="请输入面试地点" />
            </Form.Item>

            <Form.Item
              label="面试官"
              name="interviewerIds"
              rules={[{ required: true, message: '请选择面试官' }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择面试官"
                style={{ width: '100%' }}
                optionFilterProp="children"
                showSearch
              >
                {interviewers.map(interviewer => (
                  <Option 
                    key={interviewer.value} 
                    value={interviewer.value}
                  >
                    <StyledAvatar>
                      {interviewer.label}
                    </StyledAvatar>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="面试时间"
              required
            >
              <div style={{ display: 'flex', gap: '24px' }}>
                <Form.Item
                  name="startTime"
                  rules={[{ required: true, message: '请选择开始时间' }]}
                  style={{ flex: 1, margin: 0 }}
                >
                  <DatePicker
                    {...datePickerProps}
                    placeholder="开始时间"
                    disabledDate={(current) => {
                      // 开始时间不能选择过去的时间（不包括今天）
                      return current && current < dayjs().startOf('day');
                    }}
                    onChange={(value) => {
                      adjustForm.setFieldsValue({ startTime: value });
                      // 如果结束时间早于开始时间，清空结束时间
                      const endTime = adjustForm.getFieldValue('endTime');
                      if (endTime && value && endTime < value) {
                        adjustForm.setFieldsValue({ endTime: null });
                      }
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="endTime"
                  rules={[{ required: true, message: '请选择结束时间' }]}
                  style={{ flex: 1, margin: 0 }}
                >
                  <DatePicker
                    {...datePickerProps}
                    placeholder="结束时间"
                    disabledDate={(current) => {
                      const startTime = adjustForm.getFieldValue('startTime');
                      // 如果没有选择开始时间，不禁用任何日期
                      if (!startTime) {
                        return false;
                      }
                      // 将日期转换为开始时间的00:00
                      const currentStartOfDay = current?.startOf('day');
                      const startTimeStartOfDay = startTime.startOf('day');
                      
                      // 如果是同一天，允许选择
                      if (currentStartOfDay?.isSame(startTimeStartOfDay, 'day')) {
                        return false;
                      }
                      
                      // 如果不是同一天，只禁用早于开始时间的日期
                      return current && current.isBefore(startTimeStartOfDay);
                    }}
                    // 添加onChange处理，确保选择的具体时间不早于开始时间
                    onChange={(value) => {
                      const startTime = adjustForm.getFieldValue('startTime');
                      if (startTime && value && value.isBefore(startTime)) {
                        // 如果选择的时间早于开始时间，自动设置为开始时间后一小时
                        adjustForm.setFieldsValue({ 
                          endTime: startTime.add(1, 'hour') 
                        });
                      } else {
                        adjustForm.setFieldsValue({ endTime: value });
                      }
                    }}
                  />
                </Form.Item>
              </div>
            </Form.Item>
          </Form>
        </Modal>

        {/* 面试详情模态框 */}
        <Modal
          title="面试详情"
          open={detailModalVisible}
          onCancel={() => setDetailModalVisible(false)}
          width={1200}
          footer={null}
        >
          <Spin spinning={detailsLoading}>
            <Table
              dataSource={interviewDetails}
              rowKey="id"
              columns={[
                {
                  title: '应聘者',
                  dataIndex: 'name',
                  key: 'name',
                  width: 120,
                },
                {
                  title: '评分',
                  key: 'scores',
                  width: 400,
                  render: (_, record) => (
                    <Space size="large">
                      <span>
                        专业技能：
                        <Rate 
                          disabled 
                          value={record.professionalSkills}
                          style={{ color: '#1890ff' }}
                        />
                      </span>
                      <span>
                        沟通能力：
                        <Rate 
                          disabled 
                          value={record.communicationSkills}
                          style={{ color: '#52c41a' }}
                        />
                      </span>
                      <span>
                        团队协作：
                        <Rate 
                          disabled 
                          value={record.teamworkAbility}
                          style={{ color: '#faad14' }}
                        />
                      </span>
                    </Space>
                  ),
                },
                {
                  title: '综合评分',
                  dataIndex: 'overallRating',
                  key: 'overallRating',
                  width: 100,
                  render: (score: number) => (
                    <span style={{ color: '#1890ff', fontWeight: 'bold' }}>
                      {score || 0}
                    </span>
                  ),
                },
                {
                  title: '面试状态',
                  dataIndex: 'status',
                  key: 'status',
                  width: 100,
                  render: (status: number) => {
                    const statusMap = {
                      0: { text: '待面试', color: 'blue' },
                      1: { text: '已面试', color: 'green' },
                      2: { text: '已取消', color: 'red' },
                      3: { text: '未到场', color: 'orange' },
                    };
                    const config = statusMap[status as keyof typeof statusMap];
                    return <Tag color={config.color}>{config.text}</Tag>;
                  },
                },
                {
                  title: '面试结果',
                  dataIndex: 'result',
                  key: 'result',
                  width: 100,
                  render: (result: number) => {
                    const resultMap = {
                      0: { text: '待定', color: 'blue' },
                      1: { text: '通过', color: 'green' },
                      2: { text: '不通过', color: 'red' },
                    };
                    const config = resultMap[result as keyof typeof resultMap];
                    return <Tag color={config.color}>{config.text}</Tag>;
                  },
                },
                {
                  title: '评价意见',
                  dataIndex: 'comments',
                  key: 'comments',
                  render: (_, record) => (
                    <Button 
                      type="link" 
                      onClick={() => handleViewComment(record)}
                      disabled={!record.comments}
                    >
                      查看评价
                    </Button>
                  ),
                },
                {
                  title: '备注',
                  dataIndex: 'notes',
                  key: 'notes',
                  render: (_, record) => (
                    <Button 
                      type="link" 
                      onClick={() => handleViewNote(record)}
                      disabled={!record.notes}
                    >
                      查看备注
                    </Button>
                  ),
                },
                {
                  title: '简历',
                  key: 'resume',
                  render: (_, record) => (
                    <Button
                      type="link"
                      onClick={() => handleViewResume(record.intervieweeId)}
                    >
                      查看简历
                    </Button>
                  ),
                },
                {
                  title: '操作',
                  key: 'action',
                  render: (_, record) => {
                    // 如果已经评估过（status === 1），显示已评估
                    if (record.status === 1) {
                      return <Button type="text" disabled>已评估</Button>;
                    }
                    // 否则显示评估按钮
                    return (
                      <Button 
                        type="primary" 
                        size="small"
                        onClick={() => handleAssess(record, currentInterview!)}
                      >
                        评估
                      </Button>
                    );
                  },
                }
              ]}
              pagination={false}
            />
          </Spin>
        </Modal>

        {/* 评估模态框 */}
        <Modal
          title="面试评估"
          open={assessModalVisible}
          onOk={assessForm.submit}
          onCancel={() => setAssessModalVisible(false)}
          confirmLoading={detailsLoading}
          width={600}
        >
          <Form
            form={assessForm}
            onFinish={handleAssessSubmit}
            layout="vertical"
          >
            <Form.Item
              label="专业技能"
              name="professionalSkills"
              rules={[{ required: true, message: '请评分' }]}
            >
              <Rate count={5} />
            </Form.Item>
            <Form.Item
              label="沟通能力"
              name="communicationSkills"
              rules={[{ required: true, message: '请评分' }]}
            >
              <Rate count={5} />
            </Form.Item>
            <Form.Item
              label="团队协作"
              name="teamworkAbility"
              rules={[{ required: true, message: '请评分' }]}
            >
              <Rate count={5} />
            </Form.Item>
            <Form.Item
              label="评价意见"
              name="comments"
            >
              <TextArea rows={4} maxLength={500} showCount />
            </Form.Item>
            <Form.Item
              label="备注"
              name="notes"
            >
              <TextArea rows={2} maxLength={200} showCount />
            </Form.Item>
            <Form.Item
              label="面试结果"
              name="result"
              rules={[{ required: true, message: '请选择面试结果' }]}
            >
              <div style={{ display: 'flex', gap: '8px' }}>
                <div
                  onClick={() => {
                    assessForm.setFieldValue('result', 1);
                    setSelectedResult(1);
                  }}
                  style={{
                    cursor: 'pointer',
                    padding: '8px 16px',
                    border: '1px solid',
                    borderColor: selectedResult === 1 ? '#52c41a' : '#d9d9d9',
                    borderRadius: '6px',
                    backgroundColor: selectedResult === 1 ? '#52c41a' : '#ffffff',
                    color: selectedResult === 1 ? '#ffffff' : 'rgba(0, 0, 0, 0.88)',
                    fontWeight: selectedResult === 1 ? 'bold' : 'normal',
                    boxShadow: selectedResult === 1 ? '0 2px 4px rgba(0, 0, 0, 0.1)' : 'none',
                    transition: 'all 0.3s'
                  }}
                >
                  通过
                </div>
                <div
                  onClick={() => {
                    assessForm.setFieldValue('result', 2);
                    setSelectedResult(2);
                  }}
                  style={{
                    cursor: 'pointer',
                    padding: '8px 16px',
                    border: '1px solid',
                    borderColor: selectedResult === 2 ? '#ff4d4f' : '#d9d9d9',
                    borderRadius: '6px',
                    backgroundColor: selectedResult === 2 ? '#ff4d4f' : '#ffffff',
                    color: selectedResult === 2 ? '#ffffff' : 'rgba(0, 0, 0, 0.88)',
                    fontWeight: selectedResult === 2 ? 'bold' : 'normal',
                    boxShadow: selectedResult === 2 ? '0 2px 4px rgba(0, 0, 0, 0.1)' : 'none',
                    transition: 'all 0.3s'
                  }}
                >
                  不通过
                </div>
              </div>
            </Form.Item>
          </Form>
        </Modal>

        {/* 评价意见查看模态框 */}
        <Modal
          title="面试评价意见"
          open={commentModalVisible}
          onCancel={() => setCommentModalVisible(false)}
          footer={null}
          width={600}
        >
          <div className="bg-gray-50 p-4 rounded">
            {currentComment || '暂无评价意见'}
          </div>
        </Modal>

        {/* 备注查看模态框 */}
        <Modal
          title="面试备注"
          open={noteModalVisible}
          onCancel={() => setNoteModalVisible(false)}
          footer={null}
          width={600}
        >
          <div className="bg-gray-50 p-4 rounded">
            {currentNote || '暂无备注'}
          </div>
        </Modal>

        {/* 添加简历预览模态框 */}
        <Modal
          title={currentResume?.fileName || '简历预览'}
          open={resumeModalVisible}
          onCancel={handleModalClose}
          footer={[
            <Button 
              key="download" 
              onClick={() => downloadFile(previewUrl, currentResume?.fileName)}
            >
              下载
            </Button>,
            <Button key="close" onClick={handleModalClose}>
              关闭
            </Button>
          ]}
          width={1000}
          bodyStyle={{ maxHeight: '80vh', overflow: 'auto' }}
        >
          <Spin spinning={resumeLoading}>
            {previewUrl && currentResume?.fileType.includes('pdf') ? (
              <Document
                file={previewUrl}
                onLoadSuccess={({ numPages }) => setNumPages(numPages)}
              >
                {Array.from(new Array(numPages), (el, index) => (
                  <Page 
                    key={`page_${index + 1}`} 
                    pageNumber={index + 1}
                    width={800}
                  />
                ))}
              </Document>
            ) : previewUrl && currentResume?.fileType.includes('image') ? (
              <img 
                src={previewUrl} 
                style={{ maxWidth: '100%' }} 
                alt="简历预览" 
              />
            ) : (
              <div style={{ textAlign: 'center', padding: '20px' }}>
                <p>该文件类型不支持在线预览，请下载后查看</p>
                <Button 
                  type="primary" 
                  onClick={() => downloadFile(previewUrl, currentResume?.fileName)}
                  style={{ marginTop: '16px' }}
                >
                  下载文件
                </Button>
              </div>
            )}
          </Spin>
        </Modal>
      </div>
    </Layout>
  );
};

export default InterviewManagementPage;